package udp;



        import io.netty.buffer.Unpooled;
        import io.netty.channel.ChannelHandlerContext;
        import io.netty.channel.SimpleChannelInboundHandler;
        import io.netty.channel.socket.DatagramPacket;
        import io.netty.util.CharsetUtil;
        import io.netty.util.internal.ThreadLocalRandom;

/**
 * UDP Server Handler Class
 *
 * @author 胡海龙
 *
 */
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final String[] proverbs = { "只要功夫深，铁棒磨成针。", "旧时王谢堂前燕，飞入寻常百姓家。", "洛阳亲友如相问，一片冰心在玉壶。",
            "一寸光阴一寸金，寸金难买寸光阴。", "老骥伏枥，志在千里。烈士暮年，壮心不已!" };
    private static final String[] idioms = { "马到成功", "狐假虎威", "虎头虎脑", "生龙活虎", "如雷贯耳", "持之以恒" };

    /**
     * 随机返回谚语
     */
    private String nextProverb() {
        int nextInt = ThreadLocalRandom.current().nextInt(proverbs.length);
        return proverbs[nextInt];
    }

    /**
     * 随机返回成语
     */
    private String nextIdiom() {
        int nextInt = ThreadLocalRandom.current().nextInt(idioms.length);
        return idioms[nextInt];
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String message = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println("服务端接收到的消息：" + message);
        String sendMessage;
        if ("谚语".equals(message)) {
            sendMessage = nextProverb();
        } else if ("成语".equals(message)) {
            sendMessage = nextIdiom();
        } else {
            sendMessage = "请发送：“谚语”或者“成语”";
        }
        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8), msg.sender()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
